package com.agil.photoalbum.web.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.agil.photoalbum.db.dao.Functions;

/**
 * Servlet implementation class for Servlet: UploadPictureServlet
 *
 */
public class UploadPictureServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
	static final int MAX_MEMORY_SIZE = Integer.MAX_VALUE;
	static final int MAX_FILE_SIZE = Integer.MAX_VALUE;
	static final String IMAGE_REPOSITORY_PATH = "/pictures";
	private String msg = null;

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public UploadPictureServlet() {
		super();
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Create a factory for disk-based file items
		String catID = request.getParameter("catID");
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Set factory constraints
		factory.setSizeThreshold(MAX_MEMORY_SIZE);
		File repositoryPath = new File(IMAGE_REPOSITORY_PATH);
		factory.setRepository(repositoryPath);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Set overall request size constraint
		upload.setSizeMax(MAX_FILE_SIZE);
		msg = "Upload is successful";

		// Parse the request
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem fileItem = (FileItem) it.next();

				String fieldName = fileItem.getFieldName();
				String fileName = fileItem.getName();
				int index = fileName.lastIndexOf("\\");
				String fileNameWithoutPath = fileName.substring(index);
				String contentType = fileItem.getContentType();
				boolean isInMemory = fileItem.isInMemory();
				long sizeInBytes = fileItem.getSize();
				File uploadedFile = new File("D:\\Java\\Zadachi\\III.chast\\photo-album\\WebContent\\"+IMAGE_REPOSITORY_PATH + "\\" +fileNameWithoutPath);
				//
				fileItem.write(uploadedFile);
				Byte [] fileStream = Functions.getFileAsByteArray(uploadedFile);
				if(Functions.validatePicture(fileStream)){
					Functions.addPicture(fileStream, catID, uploadedFile.getName());
				}
				else {
					uploadedFile.delete();
					msg = "Faulure.Wrong Format.";
				}

			}

		} catch (FileUploadException e) {
			msg = "Faulure.Unsuccessful upload.";
			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			request.setAttribute("msg", msg);
			request.getRequestDispatcher("/pages/loadPic.jsp").forward(request,
					response);
		}

	}
}